import $ from "jquery"

export default ({
  state: {
    id: "",
    username: "",
    photo: "",
    token: "",
    is_login: false, // 用户是否登录
    pulling_info: true, // 当前是否在获取信息当中
  },
  getters: {
  },
  mutations: { // 修改数据
    updateUser(state, user) { // 更新用户信息
        state.id = user.id;
        state.username = user.username;
        state.photo = user.photo;
        state.is_login = user.is_login;
    },
    updateToken(state, token) { // 更新token信息
        state.token = token;
    },
    logout(state) {
        state.id = "";
        state.username = "";
        state.password = "";
        state.token = "";
        state.is_login = false;
    },
    updatePullingInfo(state, pulling_info) {
      state.pulling_info = pulling_info
    },
  },
  actions: {
    login(context, data) {
        $.ajax({
            url: "http://localhost:3000/user/account/token/",
            type: "post",
            data: {
              username: data.username,
              password: data.password,
            },
            success(response) {
                if (response.error_message === "success") {
                    localStorage.setItem("jwt_token", response.token);
                    context.commit("updateToken", response.token);
                    data.success(response); // 返回调用界面判断方法是否正确
                } else {
                    data.error(response);
                }
              
            },
            error(response) {
              data.error(response);
            }
          });
    },
    getInfo(context, data) { // 登录成功后得到用户信息
        $.ajax({
            url: 'http://localhost:3000/user/account/info/',
            type: "get",
            headers: {
              Authorization: "Bearer " + context.state.token,
            },
            success(response) {
                if (response.error_message === "success") {
                    context.commit("updateUser", {
                        ...response,
                        is_login: true,
                      });
        
                      data.success(response);
                } else {
                    data.error(response);
                }
              
            },
            error(response) {
              data.error(response)
            }
          });
    },
    logout(context) {
      localStorage.removeItem("jwt_token", context.state.token);
        context.commit("logout");
    }
  },
  modules: {
  }
})
